package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.R;
import com.example.reggie.dto.DishDto;
import com.example.reggie.entity.Category;
import com.example.reggie.entity.Dish;
import com.example.reggie.entity.DishFlavor;
import com.example.reggie.entity.Employee;
import com.example.reggie.service.CategoryService;
import com.example.reggie.service.DishFlavorService;
import com.example.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dishCache",key = "#dishDto.categoryId")
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
//        //清理redis缓存
//        String key="dish_"+dishDto.getCategoryId()+"_1";
//        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        //构造分页构造器对象
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name!=null,Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records=pageInfo.getRecords();
        List<DishDto> list=new ArrayList<>();

        for (Dish dish:records){
            DishDto dishDto=new DishDto();

            Long categoryId=dish.getCategoryId();//分类ID
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category!=null){
                String categoryName=category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //对象拷贝
            BeanUtils.copyProperties(dish,dishDto);

            list.add(dishDto);
        }

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 根据id来查询菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        log.info("根据id查询菜品信息");
        DishDto dishDto = dishService.getByIdWithFlavor(id);

        if (dishDto.getName()!=null){
            return R.success(dishDto);
        }
        return R.error("没有查询到对应的菜品信息");
    }

    /**
     * 更新菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "dishCache",key = "#dishDto.categoryId")
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        //清理redis缓存
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);

        return R.success("新增菜品成功");

    }

    /**
     * 根据id列表删除菜品信息
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "dishCache",allEntries = true)//disCahce里的缓存全部删除
    public R<String> delete(Long[] ids){
        log.info(ids+"");

        HashSet<String> Keys=new HashSet<>();
        for (Long id:ids
             ) {
            dishService.delete(id);

//            //记录分类id信息作为key
//            LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper();
//            queryWrapper.eq(Dish::getId,id);
//            Dish dish = dishService.getOne(queryWrapper);
//            Keys.add("dish_"+dish.getCategoryId()+"_1");
        }

//        for (String key:Keys){
//            //清理redis缓存
//            redisTemplate.delete(key);
//        }

        return R.success("菜品删除成功");
    }

    /**
     * 根据id数组和path变量更新菜品状态信息
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "dishCache",allEntries = true)//disCahce里的缓存全部删除
    public R<String> updateStatus(@PathVariable Integer status,Long[] ids){
        log.info(status+"     "+ids.toString());
        //缓存精确删除
//        HashSet<String> Keys=new HashSet<>();
        for(Long id:ids){
            LambdaUpdateWrapper<Dish> updateWrapper =new LambdaUpdateWrapper<>();
            updateWrapper.set(Dish::getStatus,status).eq(Dish::getId,id);
            dishService.update(updateWrapper);

//            //记录分类id信息作为key
//            LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper();
//            queryWrapper.eq(Dish::getId,id);
//            Dish dish = dishService.getOne(queryWrapper);
//            Keys.add("dish_"+dish.getCategoryId()+"_1");
        }


//        for (String key:Keys){
//            //清理redis缓存
//            redisTemplate.delete(key);
//        }


        return R.success("菜品状态信息修改成功");
    }


    /**
     * 根据分类id查询菜品列表
     * @param dish
     * @return
     */

    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dtoList=null;
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();

//        //先从redis中获取缓存数据
//        dtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);
//
//        if(dtoList!=null){
//            //如果存在，则直接放回，无需查询数据库
//            return R.success(dtoList);
//        }

        //如果不存在，需要查询数据库，将查询到的数据缓存到redis
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper();
        //添加查询条件
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询出菜品数据
        List<Dish> list=dishService.list(queryWrapper);
        dtoList=new ArrayList<>();

        for(Dish d:list){
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(d,dishDto);
            dtoList.add(dishDto);
        }

        for(DishDto dishDto:dtoList){
            //设置菜品的口味数据
            LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId,dishDto.getId());
            dishDto.setFlavors(dishFlavorService.list(wrapper));
            //根据ID查询分类对象
            Category category = categoryService.getById(dishDto.getCategoryId());
            dishDto.setCategoryName(category.getName());
        }

//        //将查询到的数据缓存到redis
//        redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);

        return R.success(dtoList);
    }
}
